package com.eedi.framework.mail.service;

import com.eedi.framework.common.enums.UserTypeEnum;
import com.eedi.framework.common.pojo.PageResult;
import com.eedi.framework.mail.controller.sys.vo.log.MailLogPageReq;
import com.eedi.framework.mail.dal.dataobject.SysMailLogDO;
import com.eedi.framework.mail.dal.dataobject.SysMailTemplateDO;
import com.eedi.framework.mail.dal.dataobject.SysMailAccountDO;
import com.eedi.framework.mail.dal.mapper.SysMailLogMapper;
import com.eedi.framework.mail.enums.SysMailSendStatusEnum;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * 邮件日志 Service 实现类
 *
 * @author zybourn
 * @since 2022-03-21
 */
@Service
@Validated
public class SysMailLogServiceImpl implements SysMailLogService {

    @Resource
    private SysMailLogMapper sysMailLogMapper;

    @Override
    public PageResult<SysMailLogDO> getMailLogPage(MailLogPageReq pageVO) {
        return sysMailLogMapper.selectPage(pageVO);
    }

    @Override
    public SysMailLogDO getMailLog(Long id) {
        return sysMailLogMapper.selectById(id);
    }

    @Override
    public String createMailLog(String userId, UserTypeEnum userType, String toMail,
                                SysMailAccountDO account, SysMailTemplateDO template,
                                String templateContent, Map<String, Object> templateParams, Boolean isSend) {
        SysMailLogDO.SysMailLogDOBuilder logDOBuilder = SysMailLogDO.builder();
        // 根据是否要发送，设置状态
        logDOBuilder.sendStatus(Objects.equals(isSend, true) ? SysMailSendStatusEnum.INIT
                : SysMailSendStatusEnum.IGNORE)
                // 用户信息
                .userId(userId).userType(userType).toMail(toMail)
                .sysMailAccountId(account.getSysMailAccountId()).fromMail(account.getMail())
                // 模板相关字段
                .sysMailAccountId(template.getSysMailAccountId()).templateCode(template.getCode()).templateNickname(template.getNickname())
                .templateTitle(template.getTitle()).templateContent(templateContent).templateParams(templateParams);

        // 插入数据库
        SysMailLogDO logDO = logDOBuilder.build();
        sysMailLogMapper.insert(logDO);
        return logDO.getSysLogId();
    }

    @Override
    public void updateMailSendResult(Long logId, String messageId, Exception exception) {
        // 1. 成功
        if (exception == null) {
//            mailLogMapper.updateById(new MailLogDO().setId(logId).setSendTime(LocalDateTime.now())
//                    .setSendStatus(MailSendStatusEnum.SUCCESS.getStatus()).setSendMessageId(messageId));
            return;
        }
        // 2. 失败
//        mailLogMapper.updateById(new MailLogDO().setId(logId).setSendTime(LocalDateTime.now())
//                .setSendStatus(MailSendStatusEnum.FAILURE.getStatus()).setSendException(getRootCauseMessage(exception)));

    }

}
